package com.etop.jansing.dao;

import com.etop.jansing.entities.Resource;
import com.etop.jansing.entities.ResourcePermission;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.List;

/**
 * 这是为角色而创建的，
 * 但实际上这就是一个关联关系，所以它的删除是真删除
 * Created by jansing on 2015/10/26.
 */
@Repository
public class ResourcePermissionDao extends BaseDao<ResourcePermission> {

    public void deleteResourcePermission(Resource resource) {
        Session session = getSession();
        session.createQuery("delete from  ResourcePermission rp" +
                " where rp.resource.id=:id")
                .setLong("id", resource.getId())
                .executeUpdate();
    }

    public void deleteResourcePermission(Collection<Long> ids) {
        getSession().createQuery("delete from ResourcePermission rp" +
                " where rp.id in (:ids)")
                .setParameterList("ids", ids)
                .executeUpdate();
    }

    /**
     * 在增改角色时，需要对角色所拥有的资源权限对进行操作<br/>
     * 这里通过传入一组资源权限对的id返回对应的资源权限对
     *
     * @param rpids
     * @return
     */
    public List<ResourcePermission> getResoPermListByIds(Collection<Long> rpids) {
        Session session = getSession();
        return session.createQuery("from ResourcePermission rp where rp.id in(:rpids) and rp.valid=true")
                .setParameterList("rpids", rpids)
                .list();
    }

    public List<ResourcePermission> getResoPermListByRoles(Collection<Long> roleIds){
        return getSession().createQuery("select distinct (rp) from Role r" +
                " left join r.resourcePermissionList rp" +
                " where r.id in (:roleIds)")
                .setParameterList("roleIds", roleIds)
                .list();
    }

    public ResourcePermission getByResoPermString(String resoPermString){
        return (ResourcePermission) getSession().createQuery("from ResourcePermission rp where rp.resoPermString=:resoPermString")
                .setString("resoPermString", resoPermString)
                .uniqueResult();
    }

    @Override
    public void delete(ResourcePermission resourcePermission){
        getSession().delete(resourcePermission);
    }
}
